package com.epam.cdp.jpa.filters;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.epam.cdp.jpa.utils.SessionAttributes;

public class LogoutFilter implements Filter {

    private static final Log log = LogFactory.getLog(LogoutFilter.class);
    
    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
	log.info("Handling click on logout link");
	HttpServletRequest request = (HttpServletRequest)servletRequest;
	HttpServletResponse response = (HttpServletResponse)servletResponse;
	
	String loginPageURI = request.getContextPath() + "/public/login.xhtml";
	log.info("redirecting to " + loginPageURI);
	HttpSession session = request.getSession(false);
	session.removeAttribute(SessionAttributes.USER.name());
	session.invalidate();
	
	response.sendRedirect(loginPageURI);
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {

    }

}
